package com.idudiao.sc.common.core.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.idudiao.sc.common.core.exception.base.ValidatorException;
import org.springframework.util.Assert;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * 校验工具
 *
 * @author songyinyin
 * @since 2019/2/26 11:22
 */
public class BeanValidatorUtils {

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static <T> Map<String, String> validate(T t, Class... groups) {
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap errors = new LinkedHashMap();
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation violation = (ConstraintViolation) iterator.next();
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;
        }
    }

    /**
     * 校验集合
     * @param collection 被校验的集合
     * @return {@code Map<k, v>} k - 校验不通过的字段名，v - 校验不通过的错误提示
     * @throws IllegalArgumentException 当集合为空时
     */
    public static Map<String, String> validateList(Collection<?> collection) {
        Assert.notEmpty(collection, "被校验的集合不能为空");
        Iterator iterator = collection.iterator();
        Map errors;
        do {
            if (!iterator.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());

        return errors;
    }

    /**
     * 校验对象
     * @param first 被校验的对象
     * @param objects 被校验的对象（数组）
     * @return {@code Map<k, v>} k - 校验不通过的字段名，v - 校验不通过的错误提示
     */
    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(CollUtil.toList(first, objects));
        } else {
            return validate(first, new Class[0]);
        }
    }

    /**
     * 校验对象
     * @param param 需要校验的对象
     * @throws ValidatorException 校验不通过时，抛出 校验异常
     */
    public static void check(Object param) throws ValidatorException {
        Map<String, String> map = BeanValidatorUtils.validateObject(param);
        if (MapUtil.isNotEmpty(map)) {
            throw new ValidatorException(map.toString());
        }
    }
}
